package com.duoduo.mcc.thread;

import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duoduo.mcc.bean.MccMessage;
import com.duoduo.mcc.service.MccCollectionService;
import com.duoduo.mcc.service.MccQueueService;

/**
 * 消息处理线程
 * @author cgs1999@126.com
 * @date 2018年11月1日下午6:06:20
 */
public class MccProcessThread implements Runnable {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private MccCollectionService mccCollectionService;
	private MccQueueService mccQueueService;
	private Integer ordered;// 0：无序；1：有序
	private String type;
	private String e164;
	private Random random;

	public MccProcessThread(MccCollectionService mccCollectionService, MccQueueService mccQueueService) {
		this.mccCollectionService = mccCollectionService;
		this.mccQueueService = mccQueueService;

		random = new Random(System.currentTimeMillis());
	}

	public void run() {
		if (ordered == null || ordered.equals(0)) {
			logger.debug("该消息为无序的消息，无序messageKey判断，直接执行");
			processUnorderedMessage(type);
		} else {
			// logger.debug("该消息为有序的消息，需要按照queue中顺序执行");
			// logger.debug("本次执行的e164位 {}", e164);
			logger.debug("该消息为有序的消息，需要按照queue中顺序执行");
			logger.debug("::{} 会议--::{}", e164, Thread.currentThread().toString());
			processOrderedMessage();

		}
		logger.debug("::{} 会议--::{} 结束", e164, Thread.currentThread().toString());

	}

	private void processUnorderedMessage(String type) {
		logger.debug("无序的方法执行完毕");
	}

	private void processOrderedMessage() {
		logger.debug("有序的方法执行");
		while (true) {
			List<MccMessage> listQueue = mccQueueService.getListQueue(e164);
			if (listQueue == null || listQueue.size() == 0) {
				if(mccQueueService.addMsg(e164, null)) {
					if (logger.isDebugEnabled()) {
						logger.debug("当前会议 {} 消息已经全部处理，删除当前队列中会议信息后，结束该线程", e164);
					}
					return;
				}
			} else {
				if (!mccCollectionService.conSet(e164)) {
					mccCollectionService.addSet(e164);
				}
				logger.debug("本次获取的queue的数量 {}", listQueue.size());
				mccQueueService.setRestartTime(e164, System.currentTimeMillis());
			}

			for (MccMessage queue : listQueue) {
				logger.debug("消息处理线程处理消息 {}", queue.toString());
				doSomething();
			}
		}
	}

	private void doSomething() {
		long sleep = 100 + random.nextInt(100);
		try {
			Thread.sleep(sleep);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setOrdered(Integer ordered) {
		this.ordered = ordered;

	}

	public void setType(String type) {
		this.type = type;

	}

	public void setE164(String e164) {
		this.e164 = e164;
	}
}
